package com.template.ejb.service.util;

import java.io.Serializable;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Session;

import com.template.ejb.rest.exception.JmsProducerException;
import com.template.ejb.rest.exception.ServiceLocatorException;

/**
 * 
 * 
 */
public class JMSProducer {

	private static JMSProducer INSTANCE;

	/**
	 * 
	 * @return
	 */
	public static final JMSProducer getInstance() {
		if (INSTANCE == null) {
			INSTANCE = new JMSProducer();
		}
		return INSTANCE;
	}

	/**
	 * Singleton object
	 */
	private JMSProducer() {

	}

	/**
	 * 
	 * @param payload
	 * @param connectionFactoryJndiName
	 * @param destinationJndiName
	 * @throws JmsProducerException
	 */
	public void sendMessage(Serializable payload,
			String connectionFactoryJndiName, String destinationJndiName)
			throws JmsProducerException {

		try {

			ServiceLocator serviceLocator = ServiceLocator.getInstance();

			Connection connection = null;
			Session session = null;
			Destination destination = null;
			MessageProducer messageProducer = null;
			ObjectMessage message = null;

			connection = getConnection(connectionFactoryJndiName,
					serviceLocator);

			session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

			destination = (Destination) serviceLocator
					.lookup(destinationJndiName);

			messageProducer = session.createProducer(destination);
			message = session.createObjectMessage(payload);

			messageProducer.send(message, DeliveryMode.PERSISTENT,
					Message.DEFAULT_PRIORITY, 1800000);

			messageProducer.close();
			session.close();
			connection.close();

		} catch (JMSException e) {
			throw new JmsProducerException(e);
		} catch (ServiceLocatorException e) {
			throw new JmsProducerException(e);
		}
	}

	/**
	 * 
	 * @param connectionFactoryJndiName
	 * @param serviceLocator
	 * @return
	 * @throws JMSException
	 */
	private Connection getConnection(String connectionFactoryJndiName,
			ServiceLocator serviceLocator) throws JMSException {
		ConnectionFactory connectionFactory;
		Connection connection;
		connectionFactory = (ConnectionFactory) serviceLocator
				.lookup(connectionFactoryJndiName);
		connection = connectionFactory.createConnection();
		return connection;
	}

}
